package com.hippo4j.plugin.impl;

import com.hippo4j.plugin.ExecuteAwarePlugin;

public abstract class AbstractTaskTimerPlugin implements ExecuteAwarePlugin {

    private final ThreadLocal<Long> startTimes = new ThreadLocal<>();

    @Override
    public void beforeExecute(Thread t, Runnable r) {
        startTimes.set(System.currentTimeMillis());
    }

    @Override
    public void afterExecute(Runnable r, Throwable t) {
        try {
            Long start = startTimes.get();
            if (start == null) return;
            long timeCost = System.currentTimeMillis() - start;
            System.out.println("timeCost = " + timeCost + "; thread = " + Thread.currentThread());
            processTimeCost(timeCost);
        } finally {
            startTimes.remove();
        }
    }

    protected abstract void processTimeCost(long timeCost);
}
